package com.lightkits.wms.domain.retirelib.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.FndDocumentTypeBase;
import com.lightkits.common.db.entity.FndWmMoveTypeBase;
import com.lightkits.common.db.entity.WmExecuteLine;
import com.lightkits.common.db.entity.WmRequestHeader;
import com.lightkits.common.db.entity.WmRequestLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.json.JsonUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.allot.impl.CreateDocParamsServiceImpl;
import com.lightkits.wms.domain.retirelib.CreateRetireDocParams;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.dto.retirelib.model.RetireLibDto;
import com.lightkits.wms.dto.stocktransfer.model.MiscellAdjust;
import com.lightkits.wms.util.models.LineControl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author jing.wei@hand-china.com
 * @date 2019/6/10 17:08
 **/
@Service
public class CreateRetireDocParamsImpl implements CreateRetireDocParams {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(CreateDocParamsServiceImpl.class);
   private final DocumentServiceClient client;

    @Autowired
    public CreateRetireDocParamsImpl(DocumentServiceClient client) {
        this.client = client;
    }

    /**
     * 创建领料单头信息
     *
     * @param workerId 员工Id
     * @param orgId    组织Id
     * @return
     */
    @Override
    public CheckResult<WmRequestHeader> createRequestHeader(String workerId, String orgId) {
        CheckResult<WmRequestHeader> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        WmRequestHeader header = new WmRequestHeader();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            GenerateDocNumRequestType request = new GenerateDocNumRequestType();
            request.setCount(1);
            request.setSize(5);
            request.setType("WR");
            request.setField1(df.format(new Date()));
            GenerateDocNumResponseType response = client.generateDocNumber(request);
            header.setRequestNum(response.getDocNumList().get(0));
            header.setOrganizationId(ParseUtil.tryLongWithException(orgId));
            header.setOperationType("S");
            header.setCreatorId(ParseUtil.tryLongWithException(workerId));
            header.setRequestWorkerId(ParseUtil.tryLongWithException(workerId));
            header.setExecutedWorkerId(ParseUtil.tryLongWithException(workerId));
            header.setProcessStatus("EXECUTED");
            header.setRequestType("WH_SCRAP");
            checkResult.setData(header);
        } catch (Exception e) {
            LOGGER.error("Create Request Head.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建领料单行
     *
     * @param libDtos  报废参数列表
     * @param headerId 领料单头Id
     * @return
     */
    @Override
    public CheckResult<List<WmRequestLine>> createRequestLines(List<RetireLibDto> libDtos,
                                                               Long headerId,
                                                               String moveTypeId) {
        CheckResult<List<WmRequestLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        try {
            List<WmRequestLine> lines = new ArrayList<>();
            Long num = 1L;
            for (RetireLibDto dto : libDtos) {
                WmRequestLine line = new WmRequestLine();
                line.setLineNum(new Long(num));
                line.setRequestId(headerId);
                line.setItemId(ParseUtil.tryLongWithException(dto.getScrapItemId()));
                line.setUom(dto.getUomCode());
                line.setWarehouseId(ParseUtil.tryLongWithException(dto.getWarehouseId()));
                line.setViaWarehouseId(ParseUtil.tryLongWithException(dto.getPendingWarehouseId()));
                line.setApplyQty(new BigDecimal(dto.getQty()));
                line.setLineStatus("EXECUTED");
                num += 1;
                line.setRemark(dto.getRemark());
                line.setOwnerType("OWN");
                line.setPickedFlag(true);
                line.setExeutedQty(line.getApplyQty());
                line.setLotNumber(line.getLotNumber());
                //送货单中将图片列表转换为json格式的数据进行存储
                if (!ObjectUtil.isNullOrEmpty(dto.getPictureIds())) {
                    LineControl lineControl = new LineControl();
                    lineControl.setPictureIds(dto.getPictureIds());
                    line.setLineControl(JsonUtil.toString(lineControl));
                }
                line.setMoveTypeId(ParseUtil.tryLongWithException(moveTypeId));
                line.setNgReasonId(ParseUtil.tryLongWithException(dto.getNgReasonId()));
                line.setNgReason(dto.getNgReason());
                if (!ObjectUtil.isNullOrEmpty(dto.getWmAreaId())) {
                    line.setWmAreaId(ParseUtil.tryLongWithException(dto.getWmAreaId()));
                }
                if (!ObjectUtil.isNullOrEmpty(dto.getPendingWmAreaId())) {
                    line.setViaWmAreaId(ParseUtil.tryLongWithException(dto.getPendingWmAreaId()));
                }
                lines.add(line);
            }
            checkResult.setData(lines);

        } catch (Exception e) {
            LOGGER.error("Create Request Lines  error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建领料单执行
     *
     * @param lins     领料单行信息
     * @param headerId 领料单头Id
     * @param eventId  事件ID
     * @return
     **/
    @Override
    public CheckResult<List<WmExecuteLine>> createExecuteLine(List<WmRequestLine> lins,
                                                              Long headerId, Long eventId) {
        CheckResult<List<WmExecuteLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<WmExecuteLine> executeLines = new ArrayList<>();
        try {
            for (WmRequestLine dto : lins) {
                WmExecuteLine line = new WmExecuteLine();
                line.setEventId(eventId);
                line.setItemId(dto.getItemId());
                line.setUom(dto.getUom());
                line.setDocumentLineId(dto.getId());
                line.setExecuteType("SCRAP");
                line.setExecutedQty(dto.getApplyQty());
                line.setExecutedTime(new Date());
                line.setDocumentId(headerId);
                line.setDocumentType("WH_SCRAP");
                line.setLotNumber(dto.getLotNumber());
                line.setOwnerType(dto.getOwnerType());
                line.setWarehouseId(dto.getWarehouseId());
                line.setToWarehouseId(dto.getViaWarehouseId());
                line.setWmAreaId(dto.getWmAreaId());
                line.setToWmAreaId(dto.getViaWmAreaId());
                line.setOwnerId(dto.getOwnerId());
                executeLines.add(line);
            }
            checkResult.setData(executeLines);
        } catch (Exception e) {
            LOGGER.error("Create Execute Line .error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建现有量参数
     *
     * @param requestLines  领料单行
     * @param parentEventId 父事件ID
     * @return
     */
    @Override
    public CheckResult<List<MiscellAdjust>> createOnhand(List<WmRequestLine> requestLines,
                                                         WmRequestHeader header,
                                                         String moveTypeId,
                                                         Long parentEventId
    ) {
        CheckResult<List<MiscellAdjust>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<MiscellAdjust> miscellAdjusts = new ArrayList<>();
        try {
            requestLines.forEach(line -> {
                MiscellAdjust dto = new MiscellAdjust();
                dto.setUomCode(line.getUom());
                dto.setRemark(line.getRemark());
                dto.setTransferQty(line.getApplyQty().toString());
                dto.setDirection("OUT");
                FndWmMoveTypeBase moveTypeBase = new FndWmMoveTypeBase().selectById(moveTypeId);
                dto.setMoveTypeCode(moveTypeBase.getMoveTypeCode());
                dto.setOrgId(header.getOrganizationId().toString());
                dto.setWarehouseId(line.getWarehouseId().toString());
                dto.setItemId(line.getItemId().toString());
                dto.setOwnerType("OWN");
                dto.setParentEventId(parentEventId.toString());
                dto.setWorkerId(header.getRequestWorkerId().toString());
                if (!ObjectUtil.isEmpty(line.getWmAreaId())) {
                    dto.setWmAreaId(line.getWmAreaId().toString());
                }
                dto.setDocumentId(header.getId().toString());
                FndDocumentTypeBase documentTypeBase = new FndDocumentTypeBase().selectOne(new EntityWrapper()
                        .eq(FndDocumentTypeBase.DOCUMENT_TYPE_CODE, "WH_SCRAP"));
                dto.setDocumentTypeCode("WH_SCRAP");
                dto.setDocumentNum(header.getRequestNum());
                dto.setDocumentLineId(line.getId().toString());
                miscellAdjusts.add(dto);
            });
            checkResult.setData(miscellAdjusts);
        } catch (Exception e) {
            LOGGER.error("Create Onhand Params .error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }
}
